package org.jeecg.modules.pdd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.common.util.StringUtils;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsDetailRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsPromotionUrlGenerateRequest;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkGoodsSearchRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsDetailResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsPromotionUrlGenerateResponse;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkGoodsSearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.pdd.config.PddConfig;
import org.jeecg.modules.pdd.entity.PddGoods;
import org.jeecg.modules.pdd.entity.PddGoodsCats;
import org.jeecg.modules.pdd.entity.PddPromotion;
import org.jeecg.modules.pdd.mapper.PddGoodsMapper;
import org.jeecg.modules.pdd.service.IPddGoodsCatsService;
import org.jeecg.modules.pdd.service.IPddGoodsService;
import org.jeecg.modules.pdd.service.IPddPromotionService;
import org.jeecg.modules.pdd.util.DingDanXiaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: pdd_goods
 * @Author: jeecg-boot
 * @Date: 2020-05-17
 * @Version: V1.0
 */
@Service
@Slf4j
public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoods> implements IPddGoodsService {

    @Autowired
    private IPddGoodsCatsService pddGoodsCatsService;
    @Autowired
    private IPddPromotionService pddPromotionService;

    @Override
    public void updateGoodsData() {

        List<PddGoodsCats> pddGoodsCatsList = pddGoodsCatsService.list();
        pddGoodsCatsList.forEach(pddGoodsCats -> {
            try {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.in("cat_ids_str", pddGoodsCats.getCatId());
                List<PddGoods> inpddGoodsCatsList = this.baseMapper.selectList(queryWrapper);
                Integer insize = inpddGoodsCatsList.size();
                int page = (insize * 100) / 100 + 1;
                String jsonData=DingDanXiaUtil.getPddGoodsByCatId(pddGoodsCats.getCatId(),page,null);
            //    String jsonData = getGoodsDataJson(pddGoodsCats.getCatId(), page);
                if (!StringUtils.isEmpty(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    String goods_search_response = jsonObject.getString("goods_search_response");
                    if (!StringUtils.isEmpty(goods_search_response)) {
                        JSONObject jsonObject1 = JSON.parseObject(goods_search_response);
                        String goodsJsonList = jsonObject1.getString("goods_list");
                        Long total_count = jsonObject1.getLong("total_count");
                        if (total_count > 0 && !StringUtils.isEmpty(goodsJsonList)) {
                            List<PddGoods> pddGoodsList = JSON.parseArray(goodsJsonList, PddGoods.class);
                            if (null != pddGoodsList && pddGoodsList.size() > 0) {
                                for (PddGoods pddGoods : pddGoodsList) {
                                    log.info("------------------------" + pddGoods.getGoodsId());
                                    QueryWrapper queryWrappergoods = new QueryWrapper();
                                    queryWrappergoods.in("goods_id", pddGoods.getGoodsId());
                                    List<PddGoods> pddGoods1 = this.baseMapper.selectList(queryWrappergoods);
                                    if (null == pddGoods1 || pddGoods1.size() == 0) {
                                        pddGoods.setCatIdsStr(pddGoods.getCatIds().toString());
                                        save(pddGoods);
                                        log.info("---------------------保存成功---");
                                    }


                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        });

    }

    /**
     * 排序方式:0-综合排序;1-按佣金比率升序;2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;
     * 6-按销量降序;7-优惠券金额排序升序;8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;
     * 12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;
     * 16-店铺描述评分降序;17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;
     * 20-店铺服务评分降序;27-描述评分击败同类店铺百分比升序，28-描述评分击败同类店铺百分比降序，
     * 29-物流评分击败同类店铺百分比升序，30-物流评分击败同类店铺百分比降序，
     * 31-服务评分击败同类店铺百分比升序，32-服务评分击败同类店铺百分比降序
     *
     * @param keyword
     * @param pageSize
     * @param page
     * @param sort_type
     * @param request
     * @return
     * @throws Exception
     */
    @Override
    public List<PddGoods> getSuperQueryList(String keyword, Integer pageSize, Integer page, Integer sort_type, HttpServletRequest request) throws Exception {
        PopClient client = new PopHttpClient(PddConfig.APP_KEY, PddConfig.APP_SECRET);
        PddDdkGoodsSearchRequest req = new PddDdkGoodsSearchRequest();
        req.setKeyword(keyword);

        req.setPageSize(pageSize);//每页数
        req.setPage(page);//第几页
        req.setSortType(sort_type);//按销量排序
        PddDdkGoodsSearchResponse response = client.syncInvoke(req);
        String jsonData = JsonUtil.transferToJson(response);
        if (!StringUtils.isEmpty(jsonData)) {
            JSONObject jsonObject = JSON.parseObject(jsonData);
            String goods_search_response = jsonObject.getString("goods_search_response");
            if (!StringUtils.isEmpty(goods_search_response)) {
                JSONObject jsonObject1 = JSON.parseObject(goods_search_response);
                String goodsJsonList = jsonObject1.getString("goods_list");
                Long total_count = jsonObject1.getLong("total_count");
                if (total_count > 0 && !StringUtils.isEmpty(goodsJsonList)) {
                    List<PddGoods> pddGoodsList = JSON.parseArray(goodsJsonList, PddGoods.class);
                    return pddGoodsList;
                }
            }
        }
        return null;
    }

    @Override
    public Result<?> openPddDetail(Long goodsId, String user_id) throws Exception {

        if (null == goodsId || StringUtils.isEmpty(user_id)) {
            return Result.ok("参数错误");
        }

        PddPromotion pddPromotion = pddPromotionService.getOneByUser_id(user_id);
        if (null == pddPromotion) {
            return Result.error("请联系管理员，拼多多管理问题");
        }

//        PopClient client = new PopHttpClient(PddConfig.APP_KEY, PddConfig.APP_SECRET);
//        PddDdkGoodsPromotionUrlGenerateRequest request = new PddDdkGoodsPromotionUrlGenerateRequest();
//        List<Long> goodsIdList = new ArrayList<>();
//        goodsIdList.add(goodsId);
//        request.setGoodsIdList(goodsIdList);
//        request.setPId(pddPromotion.getPid());
//        PddDdkGoodsPromotionUrlGenerateResponse response = client.syncInvoke(request);
//        String json = JsonUtil.transferToJson(response);
        Map<String, Object> resultMap = new HashMap<>();
      //  String json = DingDanXiaUtil.getDetail(String.valueOf(goodsId));
        String json = DingDanXiaUtil.getShateUrl(pddPromotion.getPid(),goodsId);
        resultMap.put("json", json);
        return Result.ok(resultMap);
    }

    @Override
    public String getProductDetail(PddGoods pddGoods) throws Exception {
        PopClient client = new PopHttpClient(PddConfig.APP_KEY, PddConfig.APP_SECRET);

        PddDdkGoodsDetailRequest request = new PddDdkGoodsDetailRequest();
        //  request.setCustomParameters("str");
        List<Long> goodsIdList = new ArrayList<Long>();
        goodsIdList.add(pddGoods.getGoodsId());
        request.setGoodsIdList(goodsIdList);
//        request.setPid("str");
//        request.setPlanType(0);
//        request.setSearchId("str");
//        request.setZsDuoId(0L);
        PddDdkGoodsDetailResponse response = client.syncInvoke(request);
        System.out.println(JsonUtil.transferToJson(response));
        return JsonUtil.transferToJson(response);
    }


    public String getGoodsDataJson(Long cid, Integer page) throws Exception {
        PopClient client = new PopHttpClient(PddConfig.APP_KEY, PddConfig.APP_SECRET);
        PddDdkGoodsSearchRequest request = new PddDdkGoodsSearchRequest();
        List<Integer> activityTags = new ArrayList<Integer>();
        activityTags.add(0);
        // request.setActivityTags(activityTags);
        request.setCatId(cid);
        // request.setCustomParameters("str");
//        List<Long> goodsIdList = new ArrayList<Long>();
//        goodsIdList.add(0L);
//        request.setGoodsIdList(goodsIdList);
//        request.setIsBrandGoods(false);
//        request.setKeyword("str");
//        request.setListId("str");
//       request.setMerchantType(0);
//        List<Integer> merchantTypeList = new ArrayList<Integer>();
//        merchantTypeList.add(0);
//        request.setMerchantTypeList(merchantTypeList);
        //  request.setOptId(0L);
        request.setPage(page);
        request.setPageSize(30);
        //  request.setPid("str");
        List<PddDdkGoodsSearchRequest.RangeListItem> rangeList = new ArrayList<PddDdkGoodsSearchRequest.RangeListItem>();

//        PddDdkGoodsSearchRequest.RangeListItem item = new PddDdkGoodsSearchRequest.RangeListItem();
//        item.setRangeFrom(0L);
//        item.setRangeId(0);
//        item.setRangeTo(0L);
//        rangeList.add(item);
//        request.setRangeList(rangeList);
        //0-综合排序;1-按佣金比率升序;2-按佣金比例降序;3-按价格升序;4-按价格降序;5-按销量升序;6-按销量降序;7-优惠券金额排序升序
        // ;8-优惠券金额排序降序;9-券后价升序排序;10-券后价降序排序;11-按照加入多多进宝时间升序;
        // 12-按照加入多多进宝时间降序;13-按佣金金额升序排序;14-按佣金金额降序排序;15-店铺描述评分升序;16-店铺描述评分降序;
        // 17-店铺物流评分升序;18-店铺物流评分降序;19-店铺服务评分升序;20-店铺服务评分降序;27-描述评分击败同类店铺百分比升序，
        // 28-描述评分击败同类店铺百分比降序，29-物流评分击败同类店铺百分比升序，30-物流评分击败同类店铺百分比降序，
        // 31-服务评分击败同类店铺百分比升序，32-服务评分击败同类店铺百分比降序
        request.setSortType(0);
        request.setWithCoupon(true);
        PddDdkGoodsSearchResponse response = client.syncInvoke(request);
        return JsonUtil.transferToJson(response);
    }


}
